package org.orion.engine;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.media.opengl.GL;



public class Shader {
	private String[] lines ;
	private int[] lengths ;
	private int id ;
	private int type;
	
	public Shader(int type){
		this.type = type;
		this.id = GLStatic.gl.glCreateShader(type);
	}
	
	public void load(String fileName){
		try {
			load( new BufferedReader( new InputStreamReader(new FileInputStream(fileName))) );
		} catch (FileNotFoundException e) {
			System.out.println(Shader.class.getName()+" "+e.getMessage());
		}
	}
	
	public void load(BufferedReader reader){
		
		try {
			String line = null;
			List<String> tempLines = new ArrayList<String>();
			while ( (line = reader.readLine())!=null ){
				if (line.trim().length()>0 && !line.trim().startsWith("//") ){
					tempLines.add(line.trim());
				}
			}
			
			lines = new String[tempLines.size()];
			lengths = new int[tempLines.size()];
			
			for (int i = 0; i < tempLines.size(); i++) {
				String tempLine = tempLines.get(i);
				lines[i] = tempLine;
				lengths[i] = tempLine.length();
			}
			
			
		} catch (IOException e) {
			System.out.println(Shader.class.getName()+" "+e.getMessage());
		}
	}
	
	
	public void glSource(){
		GLStatic.gl.glShaderSource( id, lines.length, lines, lengths, 0);
	}
	
	public void glCompile(){
		GLStatic.gl.glCompileShader(id);
		
		int[] params = new int[1];
		int[] length = new int[]{256};
		byte[] buffer = new byte[256];
		GLStatic.gl.glGetShaderiv(id, GL.GL_COMPILE_STATUS, params, 0);
		GLStatic.gl.glGetShaderInfoLog(id, buffer.length, length, 0, buffer, 0);
		if (length[0]>0){
			if (params[0]==0){
				System.out.println("Failed compile");
			}	
			System.out.println("Shader id="+id);
			System.out.println( (new String(buffer, 0, length[0])));
			System.out.println("Sources :");
			print();
		}	
		
	}
	
	private void print(){
		for (int i = 0; i < lines.length; i++) {
			System.out.println("("+i+") "+lines[i]);
		}
	}

	public int getId() {
		return id;
	}

	public int getType() {
		return type;
	}
}
